package demo3;

import java.util.Arrays;

public class Sort {

    public void quickSort(int[] arr) {
        quick(arr, 0, arr.length - 1);
    }
private void quick(int[] arr, int left, int right) {
        if(left >= right) {
            return;
        }
        //三数取中
        int mid = fundMid(arr, left, right);
        swap(arr, left, mid);
        //找基准
        int point = fundPoint(arr, left, right);
        quick(arr, left, point - 1);
        quick(arr, point + 1, right);
    }

    private void swap(int[] arr, int left, int mid) {
        int tmp = arr[left];
        arr[left] = arr[mid];
        arr[mid] = tmp;
    }

    private int fundMid(int[] arr, int left, int right) {
        int mid = (left + right) / 2;
        if(arr[left] > arr[right]) {
            if(arr[mid] > arr[left]) {
                return left;
            } else if(arr[mid] < arr[right]) {
                return right;
            } else {
                return mid;
            }
        } else {
            if(arr[mid] > arr[right]) {
                return right;
            } else if(arr[mid] < arr[left]) {
                return left;
            } else {
                return mid;
            }
        }
    }

    private int fundPoint(int[] arr, int left, int right) {
        int key = arr[left];
        while(left < right) {
            while (left < right && arr[right] >= key) {
                right--;
            }
            arr[left] = arr[right];
            while(left < right && arr[left] <= key) {
                left++;
            }
            arr[right] = arr[left];
        }
        arr[right] = key;
        return left;
    }

}

class Main {
    public static void main(String[] args) {
        int[] arr = {3,1,5,2,7,8,6};
        Sort sort = new Sort();
        sort.quickSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
